<?php
namespace Api\Controller;
use Common\Controller\ApibaseController;

/**
 * 社区
 * @package Api\Controller
 */
class BbsController extends ApibaseController {
    protected $bbs_model,$bbsComment_model,$bbsLike_model,$bbsComplain_model,$bbsFavorite_model,$image_model,$msg_model;

    public function _initialize() {
        parent::_initialize();
        $this->bbs_model = D("Bbs");
        $this->bbsComment_model = D("BbsComment");
        $this->bbsLike_model = D("BbsLike");
        $this->bbsComplain_model = M("BbsComplain");
        $this->bbsFavorite_model = M("BbsFavorite");
        $this->image_model = M("File");
        $this->msg_model = M("Message");
    }

    /**
     * 帖子列表 排序为优先显示已加精，已置顶，然后按排序值listorder属性从大到小，再ID从大到小
     * @link 访问地址 http://qiche.test2.yikeapp.cn/index.php?g=app&m=bbs&a=index
     * @see int type_id 帖子分类 1为攻略2为生意经3为用户秘诀4为用户端用户指南5为商家端用户指南
     * @see int page 当前分页数，默认1
     * 
     * @see int user_id 是否某用户帖子，默认0 不是，为其他数字时只显示该ID用户的帖子
     * @see int user_type 是否某用户帖子时需要传递的用户类型，1为普通用户2为商户
     *
     * @see int me 是否我的帖子，默认为0，为1时为显示我的帖子
     * 
     * @see string token 登录后获取的凭证,可不传意思是未登录用户
     * @see string userType 用户分类，默认为0 未登录用户为0，普通用户为1，商户为2 
     * 
     * @return json 数据行排序为按该行排序数据listorder从大到小与ID从大到小排列
     *
     * {"status":1,"message":"查询成功！","data":[{"id":"8","title":"剩下的发送到发送到","hits":"0","user_id":"35","likes":"0","comments":"0","istop":"0","isstar":"0","create_time":"2017-07-13 11:14:51","is_like":"0","username":"s2","avatar":"http://test.qicheyanghu.com/data/upload/avatar/user/20170711/5964870da08f5.png","avatar_small":"http://test.qicheyanghu.com/data/upload/avatar/user/20170711/5964870da08f5.png"}]}
     *
     *
     *              status:1为正常状态，2为请重新登录，>2为数据异常
     *              info:提示信息
     *              data:返回数据
     *                      id: 帖子ID
     *                      title: 帖子标题
     *                      content: 帖子内容
     *                      hits: 点击数
     *                      create_time: 帖子发表时间
     *                      user_id: 发帖者ID
     *                      username: 发帖者昵称
     *                      is_like: 本人是否为本帖点赞，未点为0，点击为1
     *                      is_complain: 本人是否投诉本帖，未投诉为0，已投诉为1
     *                      is_favorite: 本人收藏本帖，未收藏为0，已收藏为1
     *                      likes: 被点赞总数
     *                      istop：是否置顶，未置顶为0，已置顶为1
     *                      isstar：是否加精，未加精为0，已加精为1
     *                      comments:评论数目
     *                      avatar: 发帖者头像
     *                      avatar_small: 发帖者头像缩略图
     *                      favorite_count：被收藏数目
     *                          
     */
    public function index(){

        $type_id=I('type_id/d',0);
        $page=I('page/d',1);

        $user_type=I('user_type/d',0);
        $user_id=I('user_id/d',0);

        $me=I('me/d',0);

        $where=["b.type_id"=>$type_id,"b.status"=>1];
        if ($user_id>0) {
            $where["b.user_type"]=$user_type;
            $where["b.user_id"]=$user_id;
        }elseif($me==1){
            $where["b.user_type"]=$this->_userType;
            $where["b.user_id"]=$this->_userId;
        }

        /*$string=implode("|_|",array($user_type,$user_id,$this->_userType,$this->_userId,$page));
        $cacheName="API_BBS_LIST_CACHE_".$string;*/

        $join=$this->_getBBSJoin();
        $field=$this->_getBBSField();

        $count=$this->bbs_model
            ->alias("b")
            //->cache($cacheName."c",60)
            ->join($join)
            ->where($where)
            ->count("DISTINCT(b.id)");
        $page = $this->page($count);

        $data=$this->bbs_model
            ->alias("b")
            //->cache($cacheName,60)
            ->join($join)
            ->where($where)
            ->field($field)
            ->group("b.id")
            ->order("b.isstar DESC,b.istop DESC,b.listorder DESC,b.id DESC")
            ->limit($page->firstRow, $page->listRows)
            //->fetchSql()
            ->select();
        /*用户指南或商家指南添加页面链接*/
        if ($type_id>3) {
            foreach ($data as $key => $value) {
                $data["$key"]["link"]=U('Portal/Page/bbsPage',['id'=>$value['id']],true,true);
            }
        }

        if($data!==false){
            $this->ajaxReturn(1,$data,"查询成功！");
        }else{
            $this->ajaxReturn(0,array(),"查询错误");
        }

    }

    /**
     * 帖子内容
     * @link 访问地址 http://qiche.test2.yikeapp.cn/index.php?g=app&m=bbs&a=index
     *
     * @see string token 登录后获取的凭证,可不传意思是未登录用户
     * @see string userType 用户分类，默认为0 未登录用户为0，普通用户为1，商户为2 
     * 
     * @see int id 帖子ID
     * @return json
     *
     * {"status":1,"info":"查询成功！","data":{"id":"3","title":"楼市调控风暴持续 1天内全国6城出手限购加码","content":"在北京“10天9策”的带动下，通知还对商服类房地产项目管理、房地产市场监管等方面提出了多项规定","hits":"0","create_time":"2000-01-01 00:00:00","user_id":"1","nickname":"阿萨德","is_like":"0","likes":"0","comments":"16","images":{"2":{"id":"2","image":"http:\/\/localhost\/hua_edu_php\/data\/upload\/bbs\/201706\/593666a405655.jpg"},"3":{"id":"3","image":"http:\/\/localhost\/hua_edu_php\/data\/upload\/bbs\/201706\/593666c276203.jpg"},"4":{"id":"4","image":"http:\/\/localhost\/hua_edu_php\/data\/upload\/bbs\/201706\/593666ce495e7.jpg"},"5":{"id":"5","image":"http:\/\/localhost\/hua_edu_php\/data\/upload\/bbs\/201706\/5936697828a77.jpg"}},"istop":"1","avatar":"http:\/\/localhost\/hua_edu_php\/data\/upload\/bbs\/201704\/58f49294de370.jpg","avatar_small":"http:\/\/localhost\/hua_edu_php\/data\/upload\/bbs\/201704\/58f49294de370.jpg_small.jpg"}}
     *
     *              status:1为正常状态，2为请重新登录，>2为数据异常
     *              info:提示信息
     *              data:返回数据
     *                   id: 帖子ID
     *                   title: 帖子标题
     *                   content: 帖子内容
     *                   hits: 点击数
     *                   create_time: 帖子发表时间
     *                   user_id: 发帖者ID
     *                   nickname: 发帖者昵称
     *                   is_like: 是否为本帖点赞，未点为0，点击为1
     *                   is_complain: 本人是否投诉本帖，未投诉为0，已投诉为1
     *                   is_favorite: 本人收藏本帖，未收藏为0，已收藏为1
     *                   likes: 被点赞总数
     *                   istop：是否置顶，未置顶为0，已置顶为1
     *                   isstar：是否加精，未加精为0，已加精为1
     *                   comments:评论数目(只获取直接评论的数目，评论的评论未获取数目)
     *                   images:图片
     *                      id:图片ID
     *                      image:图片网址
     *                   avatar: 发帖者头像
     *                   avatar_small: 发帖者头像缩略图
     *                   favorite_count：被收藏数目
     *
     */
    public function getBBSInfo(){
        $id=I('id/d',0);

        if (!($id>0)){
            $this->ajaxReturn(0,array(),"ID参数错误");
        }

        $data=$this->_getBBSInfo($id);

        if($data!=false){
            $this->ajaxReturn(1,$data,"查询成功！");
        }else{
            $this->ajaxReturn(0,array(),"查询错误");
        }
    }

    private function _getBBSInfo($id){
        $where=array(
            "b.id"=>$id,
        );

        $join=$this->_getBBSInfoJoin();
        $field=$this->_getBBSInfoField();

        $data=$this->bbs_model
            ->alias("b")
            ->join($join)
            ->where($where)
            ->field($field)
            ->group("b.id")
            //->fetchSql()
            ->find();

        return $data;
    }

    /**
     * 发表帖子
     * @link 访问地址 http://qiche.test2.yikeapp.cn/index.php?g=app&m=bbs&a=addBBSInfo
     * @see string token 登录后获取的凭证 必传
     * @see int userType 用户类型，1为普通用户2为商户 必传
     * @see int type_id 帖子分类 1为攻略2为生意经3为用户秘诀4为用户端用户指南5为商家端用户指南
     * @see string title 帖子标题
     * @see string content 帖子内容
     * @see string image_ids 图片ID，逗号分隔
     *
     * @see string id 帖子ID，如果传递了即为编辑帖子
     * 
     * @return   [json]
     *
     * {"status":1,"info":"成功","data":[]}
     *
     *                status:1为正常状态，2为请重新登录，>2为数据异常
     *                info:提示信息
     *                data:返回数据
     *                  id:帖子ID
     *
     */
    public function addBBSInfo(){
        $this->checkLogin();

        $data=I("post.");
        $data=array_merge($data,[
            "user_type"=>$this->_userType,
            "user_id"=>$this->_userId
            ]);
        if (empty($data['id'])) {
            unset($data['id']);
        }
        if ($this->bbs_model->create($data)!==false) {
            if (isset($data['id'])) {
                $result=$this->bbs_model->save();
                $id=$data['id'];
            }else{
                $result=$this->bbs_model->add();
                $id=$result;
            }
            if ($result!==false) {
                $this->ajaxReturn(1,array("id"=>$id),"添加成功！");
            } else {
                $this->ajaxReturn(0,array(),"添加失败！");
            }
        } else {
            $this->ajaxReturn(0,array(),$this->bbs_model->getError());
        }
    }

    /**
     * 获取评论或者评论的评论
     * @link 访问地址 http://qiche.test2.yikeapp.cn/index.php?g=app&m=bbs&a=getComments
     *
     * @see string token 登录后获取的凭证 可不传
     * @see string userType 用户分类，默认为0 未登录用户为0，普通用户为1，商户为2  可不传
     * 
     * @see int id 帖子ID
     * @see int comment_id 评论ID，默认不传，如果传递即为获取此评论的评论
     * @see int page 当前分页数，默认1
     * @return   [json]
     *
     * {"status":1,"info":"查询成功！","data":[{"id":"46","content":"Y - 年，四位数字; 如: &quot;1999&quot; y - 年，二位数字; 如: &quot;99&quot;quot; (星期日) 至 &quot;6&quot; (星期六) a - &quot;am&quot; 或是 &quot;pm&quot; A - &quot;AM&quot; 或是 &quot;PM&quot;","create_time":"2017-04-27 09:34:57","user_id":"1","nickname":"阿萨德","avatar":"http:\/\/localhost\/hua_edu_php\/data\/upload\/bbs\/201704\/58f49294de370.jpg","comments":"1","images":{"1":{"id":"1","image":"http:\/\/localhost\/hua_edu_php\/data\/upload\/bbs\/201706\/593666a405655.jpg"},"2":{"id":"2","image":"http:\/\/localhost\/hua_edu_php\/data\/upload\/bbs\/201706\/593666a405655.jpg"},"3":{"id":"3","image":"http:\/\/localhost\/hua_edu_php\/data\/upload\/bbs\/201706\/593666c276203.jpg"}},"avatar_small":"http:\/\/localhost\/hua_edu_php\/data\/upload\/bbs\/201704\/58f49294de370.jpg_small.jpg"}]}
     *
     *                status:1为正常状态，2为请重新登录，>2为数据异常
     *                info:提示信息
     *                data:返回评论数据行
     *                          id: 评论ID
     *                          content: 评论内容
     *                          create_time: 评论发表时间
     *                          user_id: 评论者ID
     *                          nickname: 评论者昵称
     *                          avatar: 评论者头像
     *                          avatar_small: 评论者头像缩略图
     *                          comments:评论的评论数目
     *                          images:图片
     *                              id:图片ID
     *                              image:图片网址
     *
     */
    public function getComments(){
        $id=I('id/d','');
        $comment_id=I('comment_id/d',0);
        $page=I('page/d',1);

        if (!($id>0) || !($page>=0)){
            $this->ajaxReturn(0,array(),"参数错误");
        }

        $lines = $this->_getComments($id,$comment_id,$page);

        if($lines!==false){
            $this->ajaxReturn(1,$lines,"查询成功！");
        }else{
            $this->ajaxReturn(0,array(),"查询错误");
        }
    }

    /**
     * 获取单条评论信息
     * @link 访问地址 http://qiche.test2.yikeapp.cn/index.php?g=app&m=bbs&a=getCommentInfo
     * 
     * @see string token 登录后获取的凭证 可不传
     * @see string userType 用户分类，默认为0 未登录用户为0，普通用户为1，商户为2  可不传
     * 
     * @see int id 评论ID
     * @return   [json]
     *
     * {"status":1,"info":"查询成功！","data":{"id":"46","content":"Y - 年，四位数字; 如: &quot;1999&quot; y - 年，二位数字; 如 至 &quot;6&quot; (星期六) a - &quot;am&quot; 或是 &quot;pm&quot; A - &quot;AM&quot; 或是 &quot;PM&quot;","create_time":"2017-04-27 09:34:57","user_id":"1","nickname":"阿萨德","avatar":"http:\/\/localhost\/hua_edu_php\/data\/upload\/bbs\/201704\/58f49294de370.jpg","comments":"1","images":{"1":{"id":"1","image":"http:\/\/localhost\/hua_edu_php\/data\/upload\/bbs\/201706\/593666a405655.jpg"},"2":{"id":"2","image":"http:\/\/localhost\/hua_edu_php\/data\/upload\/bbs\/201706\/593666a405655.jpg"},"3":{"id":"3","image":"http:\/\/localhost\/hua_edu_php\/data\/upload\/bbs\/201706\/593666c276203.jpg"}},"avatar_small":"http:\/\/localhost\/hua_edu_php\/data\/upload\/bbs\/201704\/58f49294de370.jpg_small.jpg"}}
     *
     *                status:1为正常状态，2为请重新登录，>2为数据异常
     *                info:提示信息
     *                data:返回评论数据行
     *                          id: 评论ID
     *                          content: 评论内容
     *                          create_time: 评论发表时间
     *                          user_id: 评论者ID
     *                          nickname: 评论者昵称
     *                          avatar: 评论者头像
     *                          avatar_small: 评论者头像缩略图
     *                          comments:评论的评论数目
     *                          images:图片
     *                              id:图片ID
     *                              image:图片网址
     *
     */
    public function getCommentInfo(){
        $id=I('id/d','');

        if (!($id>0) || !($page>=0)){
            $this->ajaxReturn(0,array(),"参数错误");
        }

        $lines = $this->_getCommentInfo($id);

        if($lines!==false){
            $this->ajaxReturn(1,$lines,"查询成功！");
        }else{
            $this->ajaxReturn(0,array(),"查询错误");
        }
    }


    /**
     * 发表评论
     * @link 访问地址 http://qiche.test2.yikeapp.cn/index.php?g=app&m=bbs&a=addComment
     * @see string token 登录后获取的凭证,必传
     * @see string userType 用户分类，默认为0 未登录用户为0，普通用户为1，商户为2 
     * @see int bbs_id 帖子ID
     * @see string content 评论内容
     * @see int reply_to 如果是评论某个评论须传递此参数，可不传
     * @see int image_ids 图片ID，逗号分隔
     * @return   [json]
     *
     * {"status":1,"info":"成功","data":[]}
     *
     *                status:1为正常状态，2为请重新登录，>2为数据异常
     *                info:提示信息
     *                data:返回数据
     *
     */
    public function addComment(){
        $this->checkLogin();
        $data=array(
            "user_type"=>$this->_userType,
            "user_id"=>$this->_userId,
            "bbs_id"=>I("bbs_id/d"),
            "content"=>I("content/s"),
            "reply_to"=>I("reply_to/d",0),
            "image_ids"=>I("image_ids/s",""),
        );
        if ($this->bbsComment_model->create($data)!==false) {
            if ($this->bbsComment_model->add()!==false) {
                $this->_autoIsStar($data['bbs_id']);
                $this->_commentMessage($data['bbs_id'],$data['user_type'],$data['user_id']);
                $this->ajaxReturn(1,array(),"添加成功！");
            } else {
                $this->ajaxReturn(0,array(),"添加失败！");
            }
        } else {
            $this->ajaxReturn(0,array(),$this->bbsComment_model->getError());
        }
    }


    /**
     * 点赞或者取消赞 如果已经点赞，即为取消，如果未点赞，即为点赞
     * @link 访问地址 http://qiche.test2.yikeapp.cn/index.php?g=app&m=bbs&a=toggleLike
     * @see string token 登录后获取的凭证,必传
     * @see string userType 用户分类，默认为0 未登录用户为0，普通用户为1，商户为2 
     * @see string bbs_id 帖子ID
     * @return   [json]
     *
     * {"status":1,"info":"成功","data":[]}
     *
     *                status:1为正常状态，2为请重新登录，>2为数据异常
     *                info:提示信息
     *                data:返回数据
     *                      id: 帖子ID
     *                      title: 帖子标题
     *                      hits: 点击数
     *                      user_id: 发帖者ID
     *                      nickname: 发帖者昵称
     *                      is_like: 是否为本帖点赞，未点为0，点击为1
     *                      likes: 被点赞总数
     *                      istop：是否置顶，未置顶为0，已置顶为1
     *                      comments:评论数目
     *                      avatar: 发帖者头像
     *                      avatar_small: 发帖者头像缩略图
     *
     */
    public function toggleLike(){
        $this->checkLogin();
        $bbs_id=I("bbs_id/d",0);
        $data=array(
            "user_type"=>$this->_userType,
            "user_id"=>$this->_userId,
            "bbs_id"=>$bbs_id,
        );
        $count=$this->bbsLike_model->where($data)->count();

        //var_dump($count);exit;
        if ($count==0){
            /**
             * 数据库内不存在行，添加
             */
            if ($this->bbsLike_model->create($data)!==false) {
                if ($this->bbsLike_model->add()!==false) {
                    $info=$this->_getLikeData($bbs_id);
                    $this->ajaxReturn(1,$info,"点赞成功！");
                } else {
                    $this->ajaxReturn(0,array(),"点赞失败！");
                }
            } else {
                $this->ajaxReturn(0,array(),$this->bbsLike_model->getError());
            }
        }else{
            /**
             * 数据库内存在该行，删除
             */
            $result=$this->bbsLike_model->where($data)->limit("1")->delete();
            if ($result!=false){
                $info=$this->_getLikeData($bbs_id);
                $this->ajaxReturn(1,$info,"取消点赞成功！");
            }else{
                $this->ajaxReturn(0,array(),"取消点赞失败！");
            }
        }

    }

    private function _getLikeData($id){
        $data=$this->_getBBSInfo($id);
        unset($data['content']);unset($data['create_time']);
        return $data;
    }

    /**
     * APP接口 增加帖子点击次数 添加延迟更新,五分钟内只更新一次
     * @link 访问地址 http://qiche.test2.yikeapp.cn/index.php?g=app&m=bbs&a=addHits
     * @see string token 登录后获取的凭证
     * @see string userType 用户分类，默认为0 未登录用户为0，普通用户为1，商户为2 
     * @see string bbs_id 帖子ID
     * @return   [json]
     *
     * {"status":1,"info":"成功","data":[]}
     *
     *                status:1为正常状态，2为请重新登录，>2为数据异常
     *                info:提示信息
     *                data:返回数据
     *
     */
    public function addHits(){
        $this->checkLogin();
        $bbs_id=I('bbs_id',0);
        if ($bbs_id>0){
            $return=$this->bbs_model->where(array('id'=>$bbs_id))->setInc('hits',1,300);
            if ($return!==false) {
                $this->ajaxReturn(1,array(),"成功");
            }else{
                $this->ajaxReturn(0,array(),$this->bbs_model->getError());
            }
        }
        $this->ajaxReturn(0,array(),"ID参数错误");

    }

    /**
     * APP接口 帖子投诉
     * @link 访问地址 http://qiche.test2.yikeapp.cn/index.php?g=app&m=bbs&a=complain
     * @see int token 登录后获取的凭证
     * @see int userType 用户分类，默认为0 未登录用户为0，普通用户为1，商户为2 
     * @see int bbs_id 帖子ID
     * @see string title 投诉标题
     * @see string content 投诉内容
     * @see string image_ids 投诉附加图片，图片ID，逗号分隔
     * 
     * @return   [json]
     *
     * {"status":1,"info":"成功","data":[]}
     *
     *                status:1为正常状态，2为请重新登录，>2为数据异常
     *                info:提示信息
     *                data:返回数据
     *
     */
    public function complain(){
        $this->checkLogin();
        $data=I("post.");
        $data['user_type']=$this->_userType;
        $data['user_id']=$this->_userId;
        $return=$this->bbsComplain_model->create($data);
        $result=$this->bbsComplain_model->add();
        if ($return!==false && $result!==false) {
            $this->ajaxReturn(1,["id"=>$result],"成功");
        }else{
            $this->ajaxReturn(0,array(),$this->bbsComplain_model->getError());
        }

    }

    /**
     * APP接口 收藏或取消收藏
     * @link 访问地址 http://qiche.test2.yikeapp.cn/index.php?g=app&m=bbs&a=favorite
     * @see int token 登录后获取的凭证
     * @see int userType 用户分类，默认为0 未登录用户为0，普通用户为1，商户为2 
     * @see int bbs_id 帖子ID
     * @see int status 1为收藏，2为取消收藏
     * 
     * @return   [json]
     *
     * {"status":1,"info":"成功","data":[]}
     *
     *                status:1为正常状态，2为请重新登录，>2为数据异常
     *                info:提示信息
     *                data:返回数据
     *
     */
    public function favorite(){
        $this->checkLogin();
        $bbs_id=I("bbs_id/d",0);
        $status=I("status/d",1);
        $data=array(
            "user_type"=>$this->_userType,
            "user_id"=>$this->_userId,
            "bbs_id"=>$bbs_id,
        );

        if ($status==1){
            /**
             * 数据库内不存在行，添加
             */
            if ($this->bbsFavorite_model->create($data)!==false) {
                if ($this->bbsFavorite_model->add([],[],true)!==false) {
                    $this->ajaxReturn(1,[],"成功！");
                } else {
                    $this->ajaxReturn(0,array(),"失败！");
                }
            } else {
                $this->ajaxReturn(0,array(),$this->bbsFavorite_model->getError());
            }
        }else{
            /**
             * 数据库内存在该行，删除
             */
            $result=$this->bbsFavorite_model->where($data)->limit("1")->delete();
            if ($result!=false){
                $this->ajaxReturn(1,[],"取消成功！");
            }else{
                $this->ajaxReturn(0,array(),"取消失败！");
            }
        }

    }

    /**
     * APP接口 帖子删除
     * @link 访问地址 http://qiche.test2.yikeapp.cn/index.php?g=app&m=bbs&a=delete
     * @see string token 登录后获取的凭证
     * @see string userType 用户分类，普通用户为1，商户为2 
     * @see string bbs_id 帖子ID
     * @return   [json]
     *
     * {"status":1,"info":"成功","data":[]}
     *
     *                status:1为正常状态，2为请重新登录，>2为数据异常
     *                info:提示信息
     *                data:返回数据
     *
     */
    public function delete(){
        $this->checkLogin();
        $bbs_id=I('bbs_id',0);
        $data=array(
            "user_type"=>$this->_userType,
            "user_id"=>$this->_userId,
            "id"=>$bbs_id,
        );
        if ($bbs_id>0){
            $return=$this->bbs_model->where($data)->field("status")->save(["status"=>0]);
            if ($return!==false) {
                $this->ajaxReturn(1,array(),"成功");
            }else{
                $this->ajaxReturn(0,array(),"失败");
            }
        }
        $this->ajaxReturn(0,array(),"ID参数错误");

    }

    /**
     * 我的收藏 排序为优先显示已加精，已置顶，然后按排序值listorder属性从大到小，再ID从大到小
     * @link 访问地址 http://qiche.test2.yikeapp.cn/index.php?g=app&m=bbs&a=myFavorite
     * @see int type_id 帖子分类 1为攻略2为生意经3为用户秘诀4为用户端用户指南5为商家端用户指南
     * @see int page 当前分页数，默认1
     * 
     * @see string token 登录后获取的凭证,可不传意思是未登录用户
     * @see string userType 用户分类，默认为0 未登录用户为0，普通用户为1，商户为2 
     * 
     * @return json 数据行排序为按该行排序数据listorder从大到小与ID从大到小排列
     *
     * {"status":1,"message":"查询成功！","data":[{"id":"8","title":"剩下的发送到发送到","hits":"0","user_id":"35","likes":"0","comments":"0","istop":"0","isstar":"0","create_time":"2017-07-13 11:14:51","is_like":"0","username":"s2","avatar":"http://test.qicheyanghu.com/data/upload/avatar/user/20170711/5964870da08f5.png","avatar_small":"http://test.qicheyanghu.com/data/upload/avatar/user/20170711/5964870da08f5.png"}]}
     *
     *
     *              status:1为正常状态，2为请重新登录，>2为数据异常
     *              info:提示信息
     *              data:返回数据
     *                      id: 帖子ID
     *                      title: 帖子标题
     *                      content: 帖子内容
     *                      hits: 点击数
     *                      create_time: 帖子发表时间
     *                      user_id: 发帖者ID
     *                      username: 发帖者昵称
     *                      is_like: 本人是否为本帖点赞，未点为0，点击为1
     *                      is_complain: 本人是否投诉本帖，未投诉为0，已投诉为1
     *                      is_favorite: 本人收藏本帖，未收藏为0，已收藏为1
     *                      likes: 被点赞总数
     *                      istop：是否置顶，未置顶为0，已置顶为1
     *                      isstar：是否加精，未加精为0，已加精为1
     *                      comments:评论数目
     *                      avatar: 发帖者头像
     *                      avatar_small: 发帖者头像缩略图
     *                      favorite_time:收藏时间  
     */
    public function myFavorite(){
        $this->checkLogin();
        $type_id=I('type_id/d',0);
        $page=I('page/d',1);

        $where=["b.type_id"=>$type_id,"b.status"=>1];

        /*$string=implode("|_|",array($user_type,$user_id,$this->_userType,$this->_userId,$page));
        $cacheName="API_BBS_FAVORITE_LIST_CACHE_".$string;*/

        $join=$this->_getBBSFavoriteJoin();
        $field=$this->_getBBSFavoriteField();

        $count=$this->bbs_model
            ->alias("b")
            //->cache($cacheName."c",60)
            ->join($join)
            ->where($where)
            ->count("DISTINCT(b.id)");
        $page = $this->page($count);

        $data=$this->bbs_model
            ->alias("b")
            //->cache($cacheName,60)
            ->join($join)
            ->where($where)
            ->field($field)
            ->group("b.id")
            ->order("fa.create_time DESC")
            ->limit($page->firstRow, $page->listRows)
            //->fetchSql()
            ->select();

        if($data!==false){
            $this->ajaxReturn(1,$data,"查询成功！");
        }else{
            $this->ajaxReturn(0,array(),"查询错误");
        }

    }


    /**
     * APP接口 上传图片,大小限制10240kb
     *
     * @link 访问地址 http://qiche.test2.yikeapp.cn/index.php?g=app&m=bbs&a=addImage
     * @see string token 登录后获取的凭证
     * @see file file1 上传图片文件
     * @return   [json] 返回图片地址
     *
     * {"status":1,"info":"上传成功","data":{"id":"4","image":"bbs\/201706\/593666ce495e7.jpg","url":"http:\/\/localhost\/hua_edu_php\/data\/upload\/bbs\/201706\/593666ce495e7.jpg"}}
     *
     *              status:1为正常状态，2为请重新登录，>2为数据异常
     *              info:提示信息
     *              data:返回数据
     *                  id:图片存储ID
     *                  image: 图片存储地址
     *                  url：图片链接
     */
    public function addImage(){
       $this->checkLogin();
       $config=array(
            'rootPath'   => './'.C("UPLOADPATH"),
            'savePath'   => './file/',
            'maxSize'    => 10240000,//10240KB
            'saveName'   => array('uniqid',''),
            'exts'       =>  array('jpg', 'png', 'jpeg'),
            'autoSub'    =>  true, //自动子目录保存文件
            'subName'    =>  array('date', 'Ym'), //子目录创建方式，[0]-函数名，[1]-参数，多个参数使用数组
        );
        $upload = new \Think\Upload($config,'Local');
        $info=$upload->upload();
        //dump($info);exit;
        //开始上传
        if ($info) {
            //上传成功
            //写入附件数据库信息
            $return=true;$pathArray=[];
            foreach ($info as  $value) {
                $file=$value['savepath'].$value['savename'];
                $file=delStr($file,$config['savePath']);
                $image_url=get_bbs_image($file,"file");

                /*生成缩略图*/
                $image_dir=C("UPLOADPATH")."file/";
                $avatar_path=$image_dir.$file;
                $image = new \Think\Image();
                $image->open($avatar_path);
                $image->thumb(1280, $image->height(),1);
                $image->save($avatar_path);/*原图片保存时减小图片质量以缩小图片空间*/
                $image->thumb(640, $image->height(),1);
                $image->save($avatar_path."_small.".$value['ext']);
                unset($image);
                /*生成缩略图*/

                $data=[
                    "user_id"=>$this->_userId,
                    "path"=>"file/$file",
                    "create_time"=>date('Y-m-d H:i:s')
                ];
                $imageId=$this->image_model->add($data);
                $return=$return && $imageId;
                $pathArray[]=[
                    "type"=>"image",
                    "id"=>$imageId,
                    "url"=>$image_url
                ];
            }
            
            if($return!==false){
                $this->ajaxReturn(1,$pathArray,"上传成功");
            }else{
                $this->ajaxReturn(0,array(),$this->image_model->getError());
            }



        } else {
            //上传失败，返回错误
            $this->ajaxReturn(0,array(),$upload->getError());
        }
    }

    /**
     * 获取评论
     * @param $id 帖子ID
     * @param $comment_id 评论ID
     * @param int $page 第几页
     */
    protected function _getComments($id,$comment_id=0,$page=1){

        /*$string=implode("|_|",array($id,$comment_id,$page));
        $cacheName="API_BBS_COMMENTS_CACHE_".$string;*/

        $where=array(
            "b.bbs_id"=>$id,
            "b.status"=>1,
            "b.reply_to"=>$comment_id
        );

        $join=$this->_getCommentJoin();
        $field=$this->_getCommentField();

        $count=$this->bbsComment_model
            ->alias("b")
            ->join($join)
            ->where($where)
            ->count("distinct(b.id)");
        $page = $this->page($count);


        $data=$this->bbsComment_model
            ->alias("b")
            //->cache($cacheName,120)
            ->join($join)
            ->where($where)
            ->field($field)
            //->fetchSql()
            ->group("b.id")
            ->limit($page->firstRow, $page->listRows)
            ->select();


        return $data;
    }

    /**
     * 获取单条评论信息
     * @param $id 评论ID
     */
    protected function _getCommentInfo($id){

        $cacheName="API_BBS_COMMENT_INFO_CACHE_".$id;

        $where=array(
            "b.id"=>$id
        );

        $join=$this->_getCommentJoin();
        $field=$this->_getCommentField();


        $data=$this->bbsComment_model
            ->alias("b")
            //->cache($cacheName,120)
            ->join($join)
            ->where($where)
            ->field($field)
            //->fetchSql()
            ->group("b.id")
            ->find();

        return $data;
    }

    /**
     * 帖子自动加精 评论满50个自动加精
     * @param $id 帖子ID
     */
    protected function _autoIsStar($id){
        $cacheName="API_BBS_AUTO_ISSTAR_IDS_CACHE";
        if (S($cacheName)===false){
            $ids=[];
        }else {
            $ids=S($cacheName);
        }
        if (in_array($id,$ids)===true){
            return true;
        }else {
            $m = M();
            $query = $m->query("
                SELECT b.isstar,count(c.id) AS count
                FROM `yh_bbs` b
                LEFT JOIN `yh_bbs_comment` c ON b.id=c.bbs_id AND c.status=1
                WHERE b.id=$id
            ");
            //dump($query);
            if ($query[0]['isstar'] == 0 && $query[0]['count'] >= 50) {
                $return = $m->execute("
                    UPDATE `yh_bbs` SET isstar=1 WHERE id=$id
                ");
                if ($return === false) {
                    return false;
                }
            } elseif ($query[0]['isstar'] > 0) {
            }else{
                return false;
            }
            /**
             * 添加ID至缓存列表
             */
            $ids[]=$id;
            S($cacheName, $ids, 0);
            return false;
        }
    }


    protected function _getBBSJoin(){
        return [
            "LEFT JOIN __USER__ as u ON b.user_id=u.id AND b.user_type=1",
            "LEFT JOIN __BUSINESS__ as s ON b.user_id=s.id AND b.user_type=2",
            "LEFT JOIN __BBS_LIKE__ as l ON b.id=l.bbs_id AND l.user_type={$this->_userType} AND l.user_id={$this->_userId}",/*判断本人是否赞过*/
            "LEFT JOIN __BBS_LIKE__ as e ON b.id=e.bbs_id",/*点赞数量*/
            "LEFT JOIN __BBS_COMMENT__ as c ON b.id=c.bbs_id AND c.status=1",/*评论数量*/
            "LEFT JOIN __BBS_COMPLAIN__ as m ON b.id=m.bbs_id AND m.user_type={$this->_userType} AND m.user_id={$this->_userId}",/*是否投诉*/
            "LEFT JOIN __BBS_FAVORITE__ as f ON b.id=f.bbs_id AND f.user_type={$this->_userType} AND f.user_id={$this->_userId}",/*是否收藏*/
            "LEFT JOIN __FILE__ as i ON FIND_IN_SET(i.id,b.image_ids) >0",/*帖子图片*/
            "LEFT JOIN __BBS_FAVORITE__ as fv ON b.id=fv.bbs_id",/*收藏数量*/
        ];
    }

    protected function _getBBSInfoJoin(){
        $join=$this->_getBBSJoin();

        return $join;
    }

    protected function _getBBSFavoriteJoin(){
        $join=$this->_getBBSJoin();
        $join[]="JOIN __BBS_FAVORITE__ as fa ON b.id=fa.bbs_id AND f.user_type={$this->_userType} AND f.user_id={$this->_userId}";

        return $join;
    }

    protected function _getCommentJoin(){
        return [
            "LEFT JOIN __USER__ as u ON b.user_id=u.id AND b.user_type=1",
            "LEFT JOIN __BUSINESS__ as s ON b.user_id=s.id AND b.user_type=2",
            "LEFT JOIN __FILE__ as i ON FIND_IN_SET(i.id,b.image_ids) >0",/*评论图片*/
            "LEFT JOIN __BBS_COMMENT__ as c ON b.id=c.reply_to AND c.status=1"/*评论数量*/
        ];
    }

    protected function _getBBSField(){
        return "b.id,b.title,b.hits,b.user_id,
                coalesce(count(DISTINCT e.id),0) as likes,
                coalesce(count(DISTINCT c.id),0) as comments,
                b.istop,b.isstar,b.create_time,
                IF(l.id>0,'1','0') as is_like,
                IF(m.id,1,0) as is_complain,
                IF(f.id,1,0) as is_favorite,
                GROUP_CONCAT( DISTINCT CONCAT_WS(',',i.id,i.path) SEPARATOR '|') AS images,
                IF(b.user_type>1,s.name,u.username) as username,
                IF(b.user_type>1,s.logo,u.avatar) as avatar,
                COUNT(DISTINCT fv.id) as favorite_count";
    }

    protected function _getBBSInfoField(){
        $field=$this->_getBBSField();

        return "$field,b.content";
    }

    protected function _getBBSFavoriteField(){
        $field=$this->_getBBSField();

        return "$field,fa.create_time as favorite_time";
    }

    protected function _getCommentField(){
        return "b.id,b.content,b.create_time,b.user_id,
                coalesce(count(DISTINCT c.id),0) as comments,
                GROUP_CONCAT( distinct (CONCAT_WS(',',i.id,i.path)) SEPARATOR '|') AS images,
                IF(b.user_type>1,s.name,u.username) as username,
                IF(b.user_type>1,s.logo,u.avatar) as avatar";
    }

    /**
     * 被评论时自动添加消息
     * @DateTime 2017-07-25T09:48:14+0800
     * @param    [type]                   $id 
     * @return   [type]                       
     */
    protected function _commentMessage($id,$user_type,$user_id){
        $info=$this->bbs_model
            ->field("user_id,title")
            ->find($id);
        switch ($user_type) {
            case 1:
                $user=M('User')->where(['id'=>$user_id])->field("username")->find();
                $name="用户- ".$User['username'];
                break;
            case 2:
                $user=M('Business')->where(['id'=>$user_id])->field("name")->find();
                $name="商户- ".$User['name'];
                break;
            default:
                return false;
                break;
        }
        //插入信息表
        $title = '您的帖子- ' . $info['title'] . ' 已被评论，请打开我的帖子查看具体信息';
        $content = '您的帖子- ' . $info['title'] . ' 已被 '.$name.' 评论，请打开我的帖子查看具体信息';
        $result = lt_add_message($title, $content, $info['user_id']);
        if ($result === false) {
            return false;
        }else{
            return true;
        }
    }

}